<!--
 * @Author: WangLong
 * @Date: 2024-05-20 14:44:35
 * @LastEditTime: 2024-05-27 17:01:47
 * @LastEditors: WangLong
 * @Description: 
 * @FilePath: \front_erp\src\views\sales\projectRequirements\index.vue
-->
<template>
  <div>
    <div
      class="request"
      v-if="
        !proRequirementsAddShow &&
        !proRequirementsDtlShow &&
        !requirementsCheckShow
      "
    >
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:projectRequirements:query']"
          class="btn search"
          @click="getproRequirements"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:projectRequirements:add']"
          class="btn add"
          @click="
            proRequirementsAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >项目需求</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="projectName">项目名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectCategoryName">项目种类</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectTypeName">项目类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="executiveAddress">项目执行地</el-checkbox>
            </div>
            <div>
              <el-checkbox label="companyName">所属公司</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">所属部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="businessName">业务人员</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createUserName">申请人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createTime">创建日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="checkStatusName">审批状态</el-checkbox>
            </div>
            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-tree-select
            class="search-input"
            style="height: 100%"
            v-model="params.deptId"
            :data="deptList"
            :props="{
              value: 'deptId',
              label: 'deptName',
              children: 'children',
            }"
            value-key="deptId"
            placeholder="所属部门"
            check-strictly
            clearable
            :render-after-expand="false"
          />
        </div>
        <div class="search-item" style="margin-bottom: 10px">
          <el-select
            v-model="params.projectCategory"
            placeholder="项目种类"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in kindList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.checkStatus"
            placeholder="请选择审批状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in auditStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item" style="width: 14vw">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="至"
            start-placeholder="申请开始时间"
            end-placeholder="申请结束时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="search-item">
          <el-input
            maxlength="100"
            clearable
            v-model="params.projectNameOrCode"
            class="search-input"
            placeholder="请输入项目名称/编号查询"
          ></el-input>
        </div>
      </div>
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="projectRequirementsList"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="[0, 5, 6].includes(row.checkStatus)"
                v-hasPermi="['system:projectRequirements:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="[1].includes(row.checkStatus)"
                v-hasPermi="['system:projectRequirements:revoke']"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>

              <el-icon
                v-hasPermi="['system:projectRequirements:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="[1, 2].includes(row.checkStatus) && row.auditStatus == 1"
                v-hasPermi="['system:projectRequirements:audit']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <Checked />
              </el-icon>
              <el-icon
                v-if="[0, 5].includes(row.checkStatus)"
                v-hasPermi="['system:projectRequirements:delete']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="80"
          align="center"
        />
        <el-table-column
          label="项目名称"
          v-if="checkList.includes('projectName')"
          prop="projectName"
          :show-overflow-tooltip="true"
          min-width="200"
          sortable="custom"
        />
        <el-table-column
          label="项目种类"
          v-if="checkList.includes('projectCategoryName')"
          prop="projectCategoryName"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="项目类型"
          v-if="checkList.includes('projectTypeName')"
          prop="projectTypeName"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />

        <el-table-column
          label="项目执行地"
          v-if="checkList.includes('executiveAddress')"
          prop="executiveAddress"
          :show-overflow-tooltip="true"
          min-width="200"
          sortable="custom"
        />
        <el-table-column
          label="审批状态"
          v-if="checkList.includes('checkStatusName')"
          prop="checkStatusName"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.checkStatusName)">{{
              row.checkStatusName
            }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="下步流程"
          v-if="checkList.includes('nextNodeName')"
          prop="nextNodeName"
          :show-overflow-tooltip="true"
          min-width="150"
        />
        <el-table-column
          label="所属公司"
          v-if="checkList.includes('companyName')"
          prop="companyName"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="所属部门"
          v-if="checkList.includes('deptName')"
          prop="deptName"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        />
        <el-table-column
          label="业务人员"
          v-if="checkList.includes('businessName')"
          prop="businessName"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="申请人"
          v-if="checkList.includes('createUserName')"
          prop="createUserName"
          :show-overflow-tooltip="true"
          min-width="100"
          sortable="custom"
        />
        <el-table-column
          label="创建日期"
          v-if="checkList.includes('createTime')"
          prop="createTime"
          :show-overflow-tooltip="true"
          min-width="230"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getproRequirements"
      />
    </div>
    <ProRequirementsAdd
      ref="proRequirementsAddRef"
      v-if="proRequirementsAddShow"
      v-model:proRequirementsAddShow="proRequirementsAddShow"
      @refreshList="getproRequirements"
      :pageType="pageType"
    />
    <ProRequirementsDtl
      ref="proRequirementsDtlRef"
      v-if="proRequirementsDtlShow"
      v-model:proRequirementsDtlShow="proRequirementsDtlShow"
      @refreshList="getproRequirements"
      :pageType="pageType"
    />
    <ProRequirementsCheck
      v-if="requirementsCheckShow"
      ref="requirementsCheckRef"
      v-model:requirementsCheckShow="requirementsCheckShow"
      @refreshList="getproRequirements"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import { onMounted, provide, ref, nextTick } from "vue";
const { proxy } = getCurrentInstance();
import ProRequirementsAdd from "./proRequirementsAdd.vue";
import ProRequirementsDtl from "./proRequirementsDtl.vue";
import ProRequirementsCheck from "./proRequirementsCheck.vue";
import { getDictsApi } from "@/api/dict";
import { listDeptAll } from "@/api/system/dept";
import {
  getProjectRequirementListApi,
  getRequirementRemove,
  requirementCheck,
} from "@/api/sales/projectRequirements";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 路由
const route = useRoute();

//筛选时间
let time = ref([]);
// 搜索参数
const params = reactive({
  projectCategory: null, //项目种类
  deptId: null, //所属部门
  checkStatus: null, //审批状态
  beginTime: "", //开始日期
  endTime: "", //结束日期
  projectNameOrCode: "", // 请输入项目名称/编号查询
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 项目类型列表
const kindList = ref([]);
// 部门类型列表
const deptList = ref([]);
// 审批状态
const auditStatusList = ref([]);
// 列表数据
const projectRequirementsList = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const proRequirementsAddRef = ref(null);
const proRequirementsDtlRef = ref(null);
const requirementsCheckRef = ref(null);
// 客户新增组件显隐
const proRequirementsAddShow = ref(false);
const proRequirementsDtlShow = ref(false);
//项目审核
const requirementsCheckShow = ref(false);
// 操作类型
const pageType = ref("");

const checkList = ref([
  "projectCategoryName",
  "projectName",
  "projectTypeName",
  "executiveAddress",
  "companyName",
  "businessName",
  "checkStatusName",
  "deptName",
  "nextNodeName",
  "createUserName",
  "createTime",
]);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 59,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 59,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 获取项目列表
 */
const getproRequirements = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.beginTime = time.value[0] + " 00:00:00";
      params.endTime = time.value[1] + " 23:59:59";
    } else {
      params.beginTime = "";
      params.endTime = "";
    }
    params.auditType = 2; //1-申请页面 2-审核页面
    const res = await getProjectRequirementListApi(
      { pageNum, pageSize },
      params
    );
    projectRequirementsList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
provide("getproRequirements", getproRequirements);
/**
 * @description: 重置
 */
const handleRefresh = () => {
  time.value = [];
  Object.assign(params, {
    projectCategory: null, //项目种类
    deptId: null, //所属部门
    checkStatus: null, //审批状态
    beginTime: "", //开始日期
    endTime: "", //结束日期
    projectNameOrCode: "", // 请输入项目名称/编号查询
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getproRequirements();
};
/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getproRequirements();
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      proRequirementsAddShow.value = true;
      nextTick(() => {
        proRequirementsAddRef.value.handleDetailInfo(row);
      });
      break;
    case "detail":
      pageType.value = type;
      // proRequirementsDtlShow.value = true;
      // nextTick(() => {
      //   proRequirementsDtlRef.value.handleDetailInfo(row);
      // });
      requirementsCheckShow.value = true;
      nextTick(() => {
        requirementsCheckRef.value.handleDetailInfo(
          row.projectRequirementId,
          true
        );
      });
      break;
    case "check":
      pageType.value = type;
      requirementsCheckShow.value = true;
      nextTick(() => {
        requirementsCheckRef.value.handleDetailInfo(row.projectRequirementId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除项目需求信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await getRequirementRemove(row.projectRequirementId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getproRequirements();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "revoke":
      ElMessageBox.confirm("此操作将撤销项目需求信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          let param = {
            projectRequirementId: row.projectRequirementId,
            checkStatus: 5,
          };
          const res = await requirementCheck(param);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getproRequirements();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    default:
      break;
  }
};
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 项目种类
  await getDictsApi("erp_project_category").then((res) => {
    if (res.code === 200) {
      kindList.value = res.data;
    }
  });
  // 审批状态
  await getDictsApi("erp_non_check_status").then((res) => {
    if (res.code === 200) {
      auditStatusList.value = res.data;
    }
  });
  //部门
  listDeptAll().then((response) => {
    deptList.value = proxy.handleTree(response.data, "deptId");
  });
}
onMounted(() => {
  if (route.query?.contractId) {
    let synthesisContractId = route.query.contractId;
    pageType.value = "detail";
    proRequirementsAddShow.value = true;
    nextTick(() => {
      proRequirementsAddRef.value &&
        proRequirementsAddRef.value.handleDetailInfo(synthesisContractId);
    });
  }
  //   getTableHeader();
  getDicts();
  getproRequirements();
});
</script>

<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .search {
    flex-wrap: wrap;
  }
}
</style>
